package com.lagou.wuxi.springboottest.controller;

import com.lagou.wuxi.springboottest.entity.Blog;
import com.lagou.wuxi.springboottest.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * 博客列表页面
 */
@Controller
public class BolgController {

    @Autowired
    private BlogService blogService;

    /**
     * 博客列表
     */
    @GetMapping(value = "/blog/list")
    public String list(int page, int limit, Model model){
        if(page < 0 || limit <= 0){
            throw new IllegalArgumentException();
        }

        Page<Blog> pageResult = blogService.page(page, limit);

        model.addAttribute("blogList", pageResult.getContent());
        model.addAttribute("blogCount", pageResult.getTotalElements());
        model.addAttribute("beforePage", page-1<0?0:page-1);
        model.addAttribute("nextPage", page+1);
        model.addAttribute("lastPage", pageResult.getTotalPages());
        model.addAttribute("currentLimit", limit);
        return "index";
    }

    /**
     * 主页：重定向到博客列表
     */
    @GetMapping(value = "/")
    public String home(){
        return "redirect:/blog/list?page=0&limit=3";
    }
}
